<template>
  <div class="main">
    <div class="head"
         style="">
      <el-avatar style="float: left;margin-left: 10px" shape="square" :size="50" :src="bagInfo.imgSrc"></el-avatar>
      <div
          style="height: 60px;width: 100px;text-align: left;line-height: 30px;display: flex;flex-direction: column;justify-content: space-between">
        <span style="margin-left: 10px">{{ bagInfo.bagName }}</span>
        <span style="margin-left: 10px">{{ bagInfo.creatDate }}</span>
      </div>
    </div>
    <div class="imgContainer">
      <div class="demo-image__preview flex" v-for="(item,index) in data" :key="index" title="点击查看大图">
        <el-image
            style="width: 200px; height: 130px"
            :src="item.url"
            :preview-src-list="item.srcList"
            @click.native.prevent="getAll(item.id)"
            @contextmenu.prevent="showDetail(item.id)"
            :id="item.id"
        >
        </el-image>
        <div
            style="height: 20px;background-color:rgb(211 236 234);display: flex;flex-direction: row;justify-content: space-around;align-items: center;">
          <span>{{ item.creatDate }}</span>
          <div class="blog-info" @click="clickbest(item.id)">
            <img :src="item.isbest?require('../assets/爱心.png'):require('../assets/爱心_noclick.png')"
                 style="height: 24px;width: 20px;float: left;cursor: pointer;margin-right: 5px"/><span
              style="color: #c7c4c4;display: block;float: left;margin-top: 5px">{{ item.bestcount }}</span>
          </div>
        </div>
      </div>
    </div>
    <el-drawer
        :destroyOnClose="destroyOnClose"
        title="照片详情"
        size="80%"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClose">
      <div style="width: 100%;display: flex;flex-direction: column;justify-content: center;align-items: center">
        <div id="container" style="height: 500px;width:60%;margin: 0 auto"></div>
        <span style="margin-top: 10px">{{ address }}</span>
      </div>

      <div v-if="drawer" class="comments">
        <div style="margin: 50px 0;"></div>
        <el-input
            type="textarea"
            placeholder="请输入评论内容"
            v-model="textarea"
            maxlength="80"
            show-word-limit
        >
        </el-input>
        <div style="margin: 20px 0;"></div>
        <el-button type="danger" @click.native.prevent="addFatherComment" icon="el-icon-position" circle>xiu~
        </el-button>
        <div style="margin: 50px 0;"></div>
        <el-divider content-position="left">评论区</el-divider>
        <div class="fathercomments" v-for="(item,i) in commentermsg" :key="i">
          <div style="width: 100%;overflow: hidden;margin-bottom: 10px">
            <el-avatar style="float: left" :src="item.imgsource"></el-avatar>
            <span style="color: #409eff;cursor: pointer;float: left;margin-top: 10px;margin-left: 10px;">{{
                item.nickname
              }} :</span>
            <div class="commentofmine" style="cursor: pointer;float: left;clear: both;"
                 @click="addChild(item.commentid)" @contextmenu.prevent.stop="deleteComment(item.commentid)">
              {{ item.comment }}
              <time class="time" style="font-size: 14px;margin-left: 20px;color: #dbdbcc">{{ item.creattime }}</time>
            </div>
          </div>
          <div style="width: 100%;overflow: hidden;margin-left: 50px;margin-top: 30px;" v-for="(itt) in item.children"
               :key="itt.id">
            <el-avatar style="float: left" :src="itt.imgsource"></el-avatar>
            <span class="writername"
                  style="color: #409eff;cursor: pointer;float: left;margin-top: 10px;margin-left: 10px;">{{
                itt.nickname
              }} <strong
                  style="color: #444;font-weight: 100;font-size: 14px">回复了 : </strong> {{ itt.forname }}</span>
            <div class="commentofmine" style="cursor: pointer;float: left;clear: both;"
                 @click="addChild(itt.commentid)" @contextmenu.prevent.stop="deleteComment(itt.commentid)">
              {{ itt.comment }}
              <time class="time" style="font-size: 14px;margin-left: 20px;color: #dbdbcc">{{ itt.creattime }}</time>
            </div>
          </div>
          <el-divider content-position="right">评论分割线</el-divider>
        </div>
        <el-divider></el-divider>
      </div>


    </el-drawer>
    <el-dialog
        title="评论墙"
        :visible.sync="centerDialogVisibleChild"
        :modal="falseModal"
        width="40%"
        center
        style="z-index: 10086">
      <el-input
          type="textarea"
          placeholder="请输入评论内容"
          v-model="textarea2"
          maxlength="80"
          show-word-limit
      >
      </el-input>
      <span slot="footer" class="dialog-footer">
            <el-button @click="centerDialogVisibleChild = false,textarea2=''">取 消</el-button>
            <el-button type="primary" @click="addChildtoAfter">确 定</el-button>
          </span>
    </el-dialog>
  </div>
</template>

<script>
import AMap from 'AMap'

export default {
  name: "AlbumShow",
  data() {
    return {
      data: [],
      squareUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      bagInfo: {},
      check: false,
      drawer: false,
      destroyOnClose: true,
      direction: 'btt',
      address: "",
      loading: false,
      msg: {},
      mk: false,
      rich: false,
      textarea: "",
      commentermsg: [],
      textarea2: "",
      centerDialogVisibleChild: false,
      commentid: null,
      dialogVisible: false,
      iddd: null,
      albumId: null,
      falseModal: false,
      articleData: [],
      isOk: false,
      clicksrc: require("../assets/爱心_noclick.png"),
    }
  },
  mounted() {
    let id = this.$route.params.id
    if (id == 'x') {
      this.getAllAlbum()
      this.selectNewestByFid()
    } else {
      this.showOn(id)
      this.getBagInfo(id)
    }
  },
  methods: {
    clickbest(albumId) {
      //console.log(albumId)
      let token = window.localStorage.getItem('myToken');
      if (token == null) {
        this.$message.error("请登录后点赞！！")
        return
      }
      this.$http.put("/likeAndComment/likeOrCancel/" + albumId).then(res => {
        if (res.code == 200) {
          let arr = JSON.parse(JSON.stringify(this.data))
          arr.filter(async (item) => {
            await this.getBestCountWithArticleId(item.id).then(res => {
              item.bestcount = res
            })
            await this.checkWeatherIsSelected(item.id).then(res => {
              item.isbest = res
            })
          })
          this.data = arr
        }

      })
    },
    checkWeatherIsSelected(albumid) {
      return new Promise(resolve => {
        this.$http.get("/likeAndComment/checkWeatherIsSelected/" + albumid).then(data => {
          resolve(data.data)
        })
      })
    },
    getBestCountWithArticleId(albumid) {
      return new Promise(resolve => {
        this.$http.get("/likeAndComment/getBestCountWithAlbumId/" + albumid).then(data => {
          resolve(data.data)
        })
      })
    },
    deleteComment(commentid) {
      this.iddd = commentid
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteFinal()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteFinal() {
      this.$http.delete("/likeAndComment/delCommentByCommentId/" + this.iddd).then(data => {
        //console.log(data)
        if (data.code == 200) {
          this.dialogVisible = false
          this.$message.success("删除成功")
          this.getcomments()
        }
      })
    },
    addChild(commentid) {
      this.commentid = commentid
      let token = window.localStorage.getItem('myToken');
      if (token == null) {
        this.$message.error("请登录！！")
        return
      }
      this.centerDialogVisibleChild = true
    },
    addChildtoAfter() {
      let id = this.albumId
      if (this.textarea2 == "") {
        this.$message.error("请输入评论！！")
        return
      }
      let data = {
        comment: this.textarea2,
        albumid: id,
        parentid: this.commentid
      }
      this.$http.post('/likeAndComment/addChildComment', data).then(async res => {
        //console.log(res)
        if (res.code == 200) {
          this.textarea2 = ""
          await this.$message.success("评论成功！！")
          this.centerDialogVisibleChild = false
          this.getcomments()
        }
      })
    },
    addFatherComment() {
      let token = window.localStorage.getItem('myToken');
      if (token == null) {
        this.$message.error("请登录！！")
        return
      }
      let id = this.albumId;
      let data = {
        comment: this.textarea,
        albumid: id
      }
      if (this.textarea == "") {
        this.$message.error("请输入评论！！")
        return
      }
      this.$http.post('/likeAndComment/addFatherComment', data).then(async res => {
        //console.log(res)
        if (res.code == 200) {
          this.textarea = ""
          await this.$message.success("评论成功！！")
          this.getcomments()
        }
      })
    },
    comments(albumid) {
      return new Promise(resolve => {
        this.$http.get("/likeAndComment/getCommentsByArticle/" + albumid).then(res => {
          resolve(res.data)
        })
      })
    },
    async getcomments() {
      let id = this.albumId
      await this.comments(id).then(async res => {
        await res.filter(async (item) => {
          this.getUserInfoNotImportant(item.userid).then(async data => {
            await this.getimg(data.headPortraitId).then(data => {
              item.imgsource = data
            })
            item.nickname = data.nickname
          })
          if (item.children.length != 0) {
            item.children.filter(async (ittem) => {
              await this.getUserInfoNotImportant(ittem.userid).then(async data => {
                await this.getimg(data.headPortraitId).then(data => {
                  ittem.imgsource = data
                })
                ittem.nickname = data.nickname
              })
              await this.getUserInfoByParentid(ittem.parentid).then(data => {
                ittem.forname = data.nickname
              })
            })
          }
        })
        setTimeout(() => {
          this.commentermsg = res
        }, 800)
      })
    },
    async showCityInfo(lng, lat, id) {
      let that = this
      let map = new AMap.Map('container', {
        resizeEnable: true,
        center: [lng, lat],
        zoom: 16
      });

      await this.getImgCompress(id).then(data => {
        var infoWindow = new AMap.InfoWindow({
          anchor: 'bottom-center',
          content: '<div style="height: 50px;width: 100px;padding: 5px;margin-bottom: 15px">' +
              '<img style="width: 100%" src="' + data + '">' +
              '</div>',
        });
        infoWindow.open(map, [lng, lat]);
      })


      var geocoder = new AMap.Geocoder({
        // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        city: ''
      })

      var lnglat = [lng, lat]

      geocoder.getAddress(lnglat, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          // result为对应的地理位置详细信息
          that.address = result.regeocode.formattedAddress
        }
      })

    },
    async showDetail(id) {
      // this.commentermsg = []
      let that = this
      this.$nextTick(() => {
        this.getcomments()
      })
      this.drawer = true
      this.albumId = id
      await this.getAlbumDetail(id).then(data => {
        that.showCityInfo(data.address.split(",")[0], data.address.split(",")[1], id)
      })

    },
    getAlbumDetail(id) {
      return new Promise(resolve => {
        this.$http.get("/album/getAlbumDetail/" + id).then(data => {
          resolve(data.data)
        })
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
          })
          .catch(() => {
          });
    },
    selectNewestByFid() {
      let that = this
      that.$http.get("/album/selectNewestByFid").then(data => {
        let res = data.data
        res.bagName = "全部相片"
        that.getImgCompress(res.id).then(ret => {
          res.imgSrc = ret
        })
        res.creatDate = res.creatDate.split(" ")[0]
        that.bagInfo = res
      })
    },
    async getAllAlbum() {
      this.$http.get("/album/selectAllFamilyAlbum").then(async data => {
        data = data.data
        //console.log(data)
        for (let i = 0; i < data.length; i++) {
          await this.checkWeatherIsSelected(data[i].id).then(res => {
            if (res) {
              data[i].isbest = true
            } else {
              data[i].isbest = false
            }
          })
          await this.getBestCountWithArticleId(data[i].id).then(res => {
            data[i].bestcount = res
          })
          await this.getImgCompress(data[i].id).then(res => {
            data[i].url = res
          })
          data[i].creatDate = data[i].creatDate.split(" ")[0]
        }
        this.data = data
      })
    },
    getBagInfo(id) {
      this.$http.get("/album/selectByPrimaryKey/" + id).then(data => {
        this.getImgCompress(data.data.coverPath).then(res => {
          data.data.imgSrc = res
        })
        data.data.creatDate = data.data.creatDate.split(" ")[0]
        this.bagInfo = data.data
      })
    },
    async getAll(album_id) {
      await this.getImg(album_id).then(res => {
        let data = JSON.parse(JSON.stringify(this.data))
        for (let i = 0; i < data.length; i++) {
          if (data[i].id == album_id) {
            let arr = []
            arr.push(res)
            data[i].srcList = arr
          }
        }
        this.data = data
      })
      if (this.check == false) {
        document.getElementById(album_id).click()
        this.check = true
      } else {
        this.check = false
        return
      }
    },
    async showOn(id) {
      await this.bagCheck(id).then(async data => {
        for (let i = 0; i < data.length; i++) {
          await this.checkWeatherIsSelected(data[i].id).then(res => {
            if (res) {
              data[i].isbest = true
            } else {
              data[i].isbest = false
            }
          })
          await this.getBestCountWithArticleId(data[i].id).then(res => {
            data[i].bestcount = res
          })
          await this.getImgCompress(data[i].id).then(res => {
            data[i].url = res
          })
          data[i].creatDate = data[i].creatDate.split(" ")[0]
        }
        this.data = data
      })
    },
    bagCheck(bagId) {
      return new Promise(resolve => {
        this.$http.get("/album/selectByBagId/" + bagId).then(data => {
          resolve(data.data)
        })
      })
    },
    getImg(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/album/albumDownload/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
    getImgCompress(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/album/albumDownloadCompress/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
    getUserInfoNotImportant(userid) {
      return new Promise(resolve => {
        this.$http.get("/likeAndComment/getUserInfoNotImportant/" + userid).then(res => {
          resolve(res.data)
        })
      })
    },
    getUserInfoByParentid(parentid) {
      return new Promise(resolve => {
        this.$http.get('/likeAndComment/getUserInfoByParentid/' + parentid).then(data => {
          resolve(data.data)
        })
      })
    },
    getimg(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/file/img/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
  }
}
</script>

<style scoped>
.main {
  width: 980px;
  float: right;
}

.imgContainer {
  /*width: 100%;*/
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;
  overflow: auto;
  /*border-top: 1px dashed #eaeaea;*/
  box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 3px, rgba(0, 0, 0, 0.24) 0px 1px 2px;
  /*border-radius: 10px;*/
  padding: 10px;
}

.flex {
  position: relative;
  cursor: pointer;
  margin-left: 30px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.head {
  box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 3px, rgba(0, 0, 0, 0.24) 0px 1px 2px;
  margin-bottom: 10px;
  height: 60px;
  display: flex;
  flex-direction: row;
  justify-content: left;
  align-items: center;
}

.fathercomments {
  /*height: 70px;*/
  margin-bottom: 20px;
  overflow: hidden;
  /*background-color: red;*/
}

.is-circle {
  float: right;
}

.childpool {
  margin-left: 48px;
  margin-top: 20px;
}


.comments {
  width: 95%;
  margin: 0 auto;
}


.v-note-wrapper .v-note-panel .v-note-edit.divarea-wrapper {
  display: none !important;
}

.container >>> .el-divider__text {
  background-color: #f8f8f8;
}


.post-body img {
  margin-left: 50px;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 600px;
  height: 420px;
}

.is-circle {
  float: right;
}

.childpool {
  margin-left: 48px;
  margin-top: 20px;
}

.commentofmine {
  padding-left: 50px;
}

.post-content {
  font-size: 105%;
  line-height: 1.5rem;
  word-wrap: break-word;
  word-break: break-all;
  border-top: 1px dashed #dadada;
  border-bottom: 1px dashed #dadada;
  padding: 20px 0;
  margin-top: 25px;
}

.header {
  background-color: #fff;
}

.contain {
  padding: 15px;
  background: #fff;
  border-radius: 10px;
  position: relative;
  box-sizing: border-box;
}

.post-title {
  text-align: center;
  font-size: 1.5rem;
  margin: 20px auto;
}

.post-meta {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.writername {
  position: relative;
  /*top: -11.5px;*/
  /*left: 10px;*/
}

.el-divider--horizontal {
  display: block;
  height: 1px;
  width: 100%;
  margin: 70px 0;
}

</style>